//
//  MainTabBarViewController.m
//  Contractor
//
//  Created by star j on 16/4/18.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "MainTabBarViewController.h"
#import "PersonalViewController.h"
#import "FortuneViewController.h"
#import "SheetViewController.h"
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "CONST.h"

@interface MainTabBarViewController ()<BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,AVAudioPlayerDelegate>
{
    BMKLocationService * _locService ;
//    BMKGeoCodeSearch *_searcher ;
    double latitude ;
    double longitude ;
    NSTimer *_timer ;
    NSString *address ;
}
@end

@implementation MainTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化定位服务器
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    [_locService startUserLocationService];
    
    //开20秒定时线程
    __block MainTabBarViewController *blockSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        blockSelf->_timer=[NSTimer scheduledTimerWithTimeInterval:20.0
                                                           target:blockSelf
                                                         selector:@selector(downloadOfLocation)
                                                         userInfo:nil
                                                          repeats:YES] ;
        [[NSRunLoop currentRunLoop] addTimer:blockSelf->_timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });
    
    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(dispatchQueue, ^(void) {
        NSError *audioSessionError = nil;
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){
            NSLog(@"Successfully set the audio session.");
        } else {
            NSLog(@"Could not set the audio session");
        }
        
        
        NSBundle *mainBundle = [NSBundle mainBundle];
        NSString *filePath = [mainBundle pathForResource:@"silent" ofType:@"mp3"];
        
        NSData *fileData = [NSData dataWithContentsOfFile:filePath];
        NSError *error = nil;
        
        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
        
        if (self.audioPlayer != nil){
            self.audioPlayer.delegate = self;
            
            [self.audioPlayer setNumberOfLoops:-1];
            if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
                NSLog(@"Successfully started playing...");
            } else {
                NSLog(@"Failed to play.");
            }
        } else {
            NSLog(@"audioPlayer is nil") ;
        }
    });
    
    [self setUpAllChildVC] ;
}

- (void)setUpAllChildVC
{
    //MySheet
    SheetViewController *mysheet = [[SheetViewController alloc] init] ;
    [self setUpOneChildVC:mysheet image:[UIImage imageNamed:@"orderlist.png"] title:@"我的工单"] ;
    //FortuneCenter
    FortuneViewController *fortunecenter = [[FortuneViewController alloc] init] ;
    [self setUpOneChildVC:fortunecenter image:[UIImage imageNamed:@"account.png"] title:@"财富中心"] ;
    //PersonalCenter
    PersonalViewController *personal = [[PersonalViewController alloc] init] ;
    [self setUpOneChildVC:personal image:[UIImage imageNamed:@"personal.png"] title:@"个人中心"] ;
}

//添加一个子视图控制器
- (void)setUpOneChildVC:(UIViewController *)viewController image:(UIImage *)image title:(NSString *) title
{
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:viewController] ;
    navVC.title = title ;
    navVC.tabBarItem.image = image ;
    
    //viewController.navigationItem.title = title ;
    [self addChildViewController:navVC] ;
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    latitude = userLocation.location.coordinate.latitude ;
    longitude = userLocation.location.coordinate.longitude ;
    
    NSString *longitudeNum = [NSString stringWithFormat:@"%.6f",longitude] ;
    NSString *latitudeNum = [NSString stringWithFormat:@"%.6f",latitude] ;
    
    NSUserDefaults *Defaults = [NSUserDefaults standardUserDefaults] ;
    [Defaults setValue:latitudeNum forKey:@"latitude"] ;
    [Defaults setValue:longitudeNum forKey:@"longitude"] ;
    
    BMKGeoCodeSearch *searcher =[[BMKGeoCodeSearch alloc] init];
    searcher.delegate = self;
    //发起反向地理编码检索
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){latitude, longitude};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption =[[BMKReverseGeoCodeOption alloc] init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }

}

//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
  if (error == BMK_SEARCH_NO_ERROR) {
      NSLog(@"%@",result.address) ;
      address  = [NSString stringWithFormat:@"%@",result.address] ;
    
      NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
      [uidDefaults setValue:address forKey:@"address"] ;
  }
  else {
      NSLog(@"抱歉，未找到结果");
  }
}

#pragma mark - 定位信息上传
- (void) downloadOfLocation
{
    NSDate *date = [NSDate date] ;
    NSDateFormatter *dateFormante = [[NSDateFormatter alloc] init] ;
    [dateFormante setDateFormat:@"yyyy-MM-dd HH:mm:ss"] ;
    NSString *dateTime = [dateFormante stringFromDate:date] ;
    
    NSLog(@"latitude:%f   longitude:%f  address:%@  date:%@",latitude,longitude,address,dateTime) ;
    if (!address) {
        address = @"" ;
    }
    NSString *locationDefaults = [NSString stringWithFormat:@"中国%@",address] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    [uidDefaults setValue:locationDefaults forKey:@"location"] ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:22] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    
    NSString *longitudeNum = [NSString stringWithFormat:@"%.6f",longitude] ;
    NSString *latitudeNum = [NSString stringWithFormat:@"%.6f",latitude] ;
    
    NSDictionary *jsondic = @{@"longitude":longitudeNum,
                              @"latitude":latitudeNum,
                              @"datetime":dateTime,
                              @"address":address
                              } ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSLog(@"%@",jsondic) ;
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         
         NSLog(@"decodeStr:%@",decodeStr) ;
         
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = result ;
             NSLog(@"定位dic:%@",dic) ;
             if ([dic[@"status"]integerValue] == 1) {
                 
                 NSLog(@"定位上传成功") ;
             }
             
         }
     }
        failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
     }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
